#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>

#define BUFSIZE     8192 //pipe buf is 4096

void sig_pipe(int sig)
{
    printf("SIGPIPE caught!\n");
}

int main(int argc, char const* argv[])
{
    char buf[BUFSIZE];

    signal(SIGPIPE, sig_pipe);

    int write_fd = open("test", O_WRONLY|O_NONBLOCK);
    if (write_fd < 0)
    {
        if (errno == ENXIO)
            perror("open error ENXIO");
        else
            perror("open error");
    }
    else
        printf("open success\n");

    int read_fd = open("test", O_RDONLY|O_NONBLOCK);
    if (read_fd < 0)
        perror("open error");
    else
        printf("open success\n");

    printf("have read: %d\n", read(read_fd, buf, BUFSIZE));

    write_fd = open("test", O_WRONLY|O_NONBLOCK);
    if (write_fd < 0)
    {
        if (errno == ENXIO)
            perror("open error ENXIO");
        else
            perror("open error");
    }
    else
        printf("open success\n");

    close(read_fd);
    
    if (write(write_fd, buf, BUFSIZE) < 0)
    {
        if (errno == EPIPE)
            perror("write error EPIPE");
        else
            perror("write error");
    }

    read_fd = open("test", O_RDONLY|O_NONBLOCK);
    if (read(read_fd, buf, BUFSIZE) < 0)
    {
        if (errno == EAGAIN)
            perror("read error EAGAIN");
        else
            perror("read error");
    }

    printf("pipe buf is %ld\n", fpathconf(write_fd, _PC_PIPE_BUF));
    
    if (write(write_fd, buf, BUFSIZE) < 0)
    {
        if (errno == EAGAIN)
            perror("write error EAGAIN");
        else
            perror("write error");
    }
    else
        printf("write success\n");

    int have_write;
    while ((have_write = write(write_fd, buf, BUFSIZE)) > 0)
        printf("have write:%d\n", have_write);
    if (errno == EAGAIN)
        perror("write error EAGAIN");
    else
        perror("write error");

    return 0;
}
